package com.example.jdimust.account;

/**
 * Author: MaZongyang
 * Date: 2021/5/19/0019 15:24
 * Description:
 */

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.jdimust.util.ACache;
import com.example.jdimust.util.Formatting;
import com.example.jdimust.util.MessageCheck;
import com.example.jdimust.register.NetworkRequest;
import com.example.jdimust.R;
import com.example.jdimust.upload.UploadCreateAccountActivity;
import com.example.jdimust.value.ValueActivity;
import com.example.jdimust.login.LoginActivity;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import static android.os.Build.VERSION.SDK_INT;

public class AccountActivity extends AppCompatActivity {


    private List<Account> AccList = new ArrayList<>();
    private ACache acache;//缓存框架
    private Button bt_creacc;

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (SDK_INT < Build.VERSION_CODES.P) {
            return;
        }
        try {
            Method forName = Class.class.getDeclaredMethod("forName", String.class);
            Method getDeclaredMethod = Class.class.getDeclaredMethod("getDeclaredMethod", String.class, Class[].class);
            Class<?> vmRuntimeClass = (Class<?>) forName.invoke(null, "dalvik.system.VMRuntime");
            Method getRuntime = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "getRuntime", null);
            Method setHiddenApiExemptions = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "setHiddenApiExemptions", new Class[]{String[].class});
            Object sVmRuntime = getRuntime.invoke(null);
            setHiddenApiExemptions.invoke(sVmRuntime, new Object[]{new String[]{"L"}});
        } catch (Throwable e) {
            Log.e("[error]", "reflect bootstrap failed:", e);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);


        bt_creacc = (Button) findViewById(R.id.bt_create_account);
        acache=ACache.get(this);//创建ACache组件
        Intent intent = getIntent();
//        String ledgerid = intent.getStringExtra("ledgerid");
//        String ledgerHash = intent.getStringExtra("ledgerHash");;
//        String ledgerName = intent.getStringExtra("ledgerName");

        String togetjson = NetworkRequest.getaccount("/GetMessage/account?lid=",acache.getAsString("acaledgerid"),"");
        Gson gson = new Gson();
        AccountBean accbean = gson.fromJson(togetjson, AccountBean.class);
        for (AccountBean.ResultDTO resultDTO : accbean.getResult()) {
            String accname = resultDTO.getAccountName();
            String accid = resultDTO.getId();
            String accsta = resultDTO.getState();
            String acccrttime = resultDTO.getAccountCreateTime();
            long time1 = Long.valueOf(acccrttime).longValue();
            String account_create_time;
            account_create_time = Formatting.stampToDate(time1);

            String accche = "{\n" +
                    "\"ledgerHash\": \"" + acache.getAsString("acaledgerHash") + "\",\n" +
                    "\"accountData\": [\n" +
                    "{\n" +
                    "\"id\":" + resultDTO.getId() + ",\n" +
                    "\"accountName\": \"" + resultDTO.getAccountName() + "\",\n" +
                    "\"accountHash\": \"" + resultDTO.getAccountHash() + "\",\n" +
                    "\"blockHeight\": " + resultDTO.getBlockHeight() + ",\n" +
                    "\"accountCreateTime\": " + resultDTO.getAccountCreateTime() + ",\n" +
                    "\"accountUid\": " + resultDTO.getAccountUid() + ",\n" +
                    "\"accountLid\": " + resultDTO.getAccountLid() + ",\n" +
                    "\"state\": \"" + resultDTO.getState() + "\"\n" +
                    "}\n" +
                    "]\n" +
                    "}";
            String restate = null;
            try {
                restate = MessageCheck.mescheck("/account", accche);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Account account = new Account(accname, accid, account_create_time, restate, resultDTO.getAccountHash());
            AccList.add(account);
        }

//        getaccount(acache.getAsString("acaledgerid"), ledgerHash);
        AccountAdapter adapter1 = new AccountAdapter(AccountActivity.this, R.layout.acc_item, AccList);
        ListView listView = (ListView) findViewById(R.id.lv_accmes);
        listView.setAdapter(adapter1);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView viewByaccid = (TextView) view.findViewById(R.id.acc_lv_id);
                TextView viewByAccname = (TextView) view.findViewById(R.id.acc_lv_accname);
                TextView viewByacchash = (TextView) view.findViewById(R.id.acc_lv_acchash);
//                Intent intent = new Intent(AccountActivity.this, ValueActivity.class);
//                intent.putExtra("accounthash", viewByacchash.getText());//参数：name、value
//                intent.putExtra("accountname", viewByAccname.getText());//参数：name、value
                String accname = (String) viewByAccname.getText();
                String acchash = (String) viewByacchash.getText();
//                intent.putExtra("accountid", viewByaccid.getText());//参数：name、value
                String accid =  viewByaccid.getText().toString();
//                String accid = (String) viewByAccname.getText();
                acache.put("acaaccountid", accid);
                acache.put("acaaccountName", accname);
                acache.put("acaaccountHash", acchash);
//                acache.put("accountid",accid);
//                intent.putExtra("ledgerHash", ledgerHash);//参数：name、value
                startActivity(new Intent(AccountActivity.this, ValueActivity.class));
//                Toast.makeText(AccountActivity.this, "Click item" + i, Toast.LENGTH_SHORT).show();
            }
        });
        bt_creacc.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent(AccountActivity.this, UploadCreateAccountActivity.class);
                startActivity(new Intent(AccountActivity.this, UploadCreateAccountActivity.class));
                finish();
            }
        });
    }
        /*
    private void getaccount(String ledgerid, String ledgerHash) {
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
        try  {
            Request request = new Request.Builder()
                    .url("https://hzy.graduationproject.xyz/GetMessage/account?lid=" + ledgerid)//请求接口。如果需要传参拼接到接口后面。
                    .build();//创建Request 对象
            Response response = null;
            response = client.newCall(request).execute();//得到Response 对象
            if (response.isSuccessful()) {
                String getallacc = response.body().string();
                Gson gson1 = new Gson();
                JSONObject alledmesjson = new JSONObject(getallacc);
                String allaccresult = alledmesjson.optString("result", null);
                AccBean accbean = gson1.fromJson(getallacc, AccBean.class);
                System.out.println(accbean.getFlag());
                for (AccBean.ResultDTO resultDTO : accbean.getResult()) {
                    String accname = resultDTO.getAccountName();
                    String accid = resultDTO.getId();
                    String accsta = resultDTO.getState();
                    String acccrttime = resultDTO.getAccountCreateTime();
                    long time1 = Long.valueOf(acccrttime).longValue();
                    String account_create_time;
                    account_create_time = Formatting.stampToDate(time1);

                    String accche = "{\n" +
                            "\"ledgerHash\": \"" + ledgerHash + "\",\n" +
                            "\"accountData\": [\n" +
                            "{\n" +
                            "\"id\":" + resultDTO.getId() + ",\n" +
                            "\"accountName\": \"" + resultDTO.getAccountName() + "\",\n" +
                            "\"accountHash\": \"" + resultDTO.getAccountHash() + "\",\n" +
                            "\"blockHeight\": " + resultDTO.getBlockHeight() + ",\n" +
                            "\"accountCreateTime\": " + resultDTO.getAccountCreateTime() + ",\n" +
                            "\"accountUid\": " + resultDTO.getAccountUid() + ",\n" +
                            "\"accountLid\": " + resultDTO.getAccountLid() + ",\n" +
                            "\"state\": \"" + resultDTO.getState() + "\"\n" +
                            "}\n" +
                            "]\n" +
                            "}";
                    String restate = MessageCheck.mescheck("/account", accche);
                    Account account = new Account(accname, accid, account_create_time, restate,resultDTO.getAccountHash());
                    AccList.add(account);
                }
//                JSONObject alledmesjson = new JSONObject(getallacc);
//                String allres = alledmesjson.optString("result", null);
////                JSONArray jsonArray = new JSONArray(allres);
//                System.out.println(allres);
//                for (int j = 0; j < jsonArray.length(); j++) {
//                    JSONObject jsonobj = jsonArray.getJSONObject(j);
////                    String ledgerName = jsonobj.optString("ledgerName", null);
//                }
//                Log.d(TAG, "flag" + msg);
                //此时的代码执行在子线程，修改UI的操作请使用handler跳转到UI线程。
            }
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("somethings");
        }
    }*/

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return true;
    }

    /**
     *菜单的点击事件
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case R.id.chageuser:
                Toast.makeText(this, "正在切换用户！", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(AccountActivity.this, LoginActivity.class);//从SpendingActivity页面跳转至ExpenseProcesActivity页面
                startActivity(intent);
                break;
            default:
                break;
        }

        return true;
    }



}